/**
 * 
 */
package com.csair.youth.service.impl;

import javax.mail.MessagingException;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.apache.log4j.Logger;

import com.csair.youth.database.User;

/**
 * @author mickey
 *
 */
public class EmailServiceImpl {
	private static final Logger log = Logger.getLogger(EmailServiceImpl.class);
	
	private String smtpServer;
	private int smtpPort; 
	private String userName;
	private String password;
	private boolean useSSL;
	private boolean useTLS;
	
	public String getSmtpServer() {
		return smtpServer;
	}
	public void setSmtpServer(String smtpServer) {
		this.smtpServer = smtpServer;
	}
	public int getSmtpPort() {
		return smtpPort;
	}
	public void setSmtpPort(int smtpPort) {
		this.smtpPort = smtpPort;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	public boolean isUseSSL() {
		return useSSL;
	}
	public void setUseSSL(boolean useSSL) {
		this.useSSL = useSSL;
	}
	public boolean isUseTLS() {
		return useTLS;
	}
	public void setUseTLS(boolean useTLS) {
		this.useTLS = useTLS;
	}
	
	public void sendMail(User recv, String title, String content) throws EmailException, MessagingException{
		if(recv == null){
			log.error("没有指定收件人，不发送邮件...");
			return;
		}
		Email mail = new SimpleEmail();
		mail.setCharset("UTF-8");
		mail.setHostName(smtpServer);
		mail.setSmtpPort(smtpPort);
		mail.setAuthenticator(new DefaultAuthenticator(userName, password));
		mail.setSSL(useSSL);
		mail.setTLS(useTLS);
		mail.setFrom(userName, "青年资源库");
		mail.addTo(recv.getEmail(), recv.getName());
		mail.setSubject(title);
//		mail.setMsg(content);   用这句不支持中文
		mail.buildMimeMessage();
		mail.getMimeMessage().setText(content, "UTF-8");
		mail.sendMimeMessage();
		log.warn("系统发送邮件,TO:"+recv.getName()+",TITLE:"+title+",CONTENT:"+content);
	}
}
